package wordCount;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordCount {

	

	public static int countChar(String strs) {
		char c ;
		int sum = 0;
		for (int i = 0; i < strs.length(); i++) {
	         c = strs.charAt(i);
	         if (c >= 32 && c <= 126 || c == '\r' || c == '\n'|| c == '\t') {
	             sum++;
	         }
	     }
		return sum;
	}

	public static int countLines(String[] strs) {
		int sum = 0;
		for (int i = 0; i < strs.length; i++) {
			if ( strs[i] == null) {
				break;
			} 
			if (strs[i].trim().length() == 0 || strs[i].trim().equals("")) {
				continue;
			}
			sum++;
		}
		return sum;
	}

	public static ArrayList<String> countWords(String[] strs) {
		ArrayList<String> result = new ArrayList<String>();
		Map<String, Integer> map = new HashMap<String, Integer>();
		Pattern p = Pattern.compile("\\b[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z][A-Za-z0-9]*\\b");
		for (int i = 0; i < strs.length; i++) {
			if ( strs[i] == null) {
				continue;
			} 
			if (strs[i].length() == 0 || strs[i].equals("")) {
				continue;
			}
			Matcher m = p.matcher(strs[i]);
			while (m.find()) {
				String mstr = m.group();
				if (map.containsKey(mstr)) {
					map.put(mstr, map.get(mstr) + 1);
				} else {
					map.put(mstr, 1);
				}
			}
		}
		List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				if (o1.getValue() == o2.getValue()) {
					return o1.getKey().compareTo(o2.getKey());
				}
				return o2.getValue() - o1.getValue();
			}

		});
		for(Map.Entry<String,Integer> mapping:list){ 
		result.add("<"+mapping.getKey().toLowerCase()+">" + ": " + mapping.getValue());
      } 
		
		return result;
	}
}
